const db = require('../common/db');
const sql = require('../common/sql');

module.exports = {
    addcart: (req, res) => {
        let { userid, goods, num } = req.body;
        db.query(sql.carts.cartsByUG, [userid, goods.gid], (err, results) => {
            if (err) {
                res.send({ code: 500, msg: err.message });
            } else {
                if (results.length > 0) {
                    //更新数量
                    db.query(sql.carts.updateNum, [num, userid, goods.gid], (err1, resluts1) => {
                        if (err1) {
                            res.send({ code: 500, msg: err1.message });
                        } else {
                            res.send({ code: 200, msg: '已更新购物车商品的数量。' })
                        }
                    });
                } else {
                    //添加
                    db.query(sql.carts.addcart, [userid, goods.gid, goods.price, num], (err1, resluts1) => {
                        if (err1) {
                            res.send({ code: 500, msg: err1.message });
                        } else {
                            res.send({ code: 200, msg: '已成功添加到购物车。' })
                        }
                    });
                }
            }
        })
    },
    changeNum: (req, res) => {
        let { cartid, num } = req.body;
        db.query(sql.carts.changeNum, [num, cartid], (err, results) => {
            if (err) {
                res.send({ code: 500, msg: err.message });
            } else {
                res.send({ code: 200 });
            }
        })
    },
    cartList: (req, res) => {
        let userid = req.body.userid;
        db.query(sql.carts.cartList, [userid], (err, results) => {
            if (err) {
                res.send({ code: 500, msg: err.message });
            } else {
                res.send({ code: 200, carts: results });
            }
        })
    }
}